package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.Cart;
import ysq.xyg.model.info.CartInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.CartService;
import ysq.xyg.service.ItemService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Date;

/**
 * 购物车
 *
 * @author congcong tao
 * @create 2018/8/9 下午11:01
 */
@Controller
@RequestMapping("/cart")
public class CartController extends BaseController {

    private static Logger log= LoggerFactory.getLogger(CartController.class);
    @Resource
    private CartService cartService;
    @Resource
    private ItemService itemService;

    private Cart cart;

    @RequestMapping("/listPage")
    public ModelAndView list(String status){
        ModelAndView view = new ModelAndView("/cartList");
        view.addObject("status", status);
        return view;
    }

    @RequestMapping(value = "/jsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject jsonList(Cart cart, Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<Cart> pageInfo = cartService.pageInfo(cart, page.getLimit(), page.getPage());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", pageInfo.getTotal());
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for (Cart item : pageInfo.getList()) {
                row = new JSONObject();
                row.put("id", item.getId());
                row.put("price", item.getItem().getPrice());
                row.put("imageOne", item.getItem().getImageOne());
                row.put("itemTitle", item.getItem().getTitle());
                row.put("itemId", item.getItemId());
                row.put("totalNum", item.getTotalNum());
                row.put("readyNum", item.getReadyNum());
                row.put("activityId", item.getActivityId());
                row.put("periodsNum", item.getPeriodsNum());
                row.put("personNum", item.getItem().getPersonNum());
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/selectEntity",method = RequestMethod.GET)
    public ModelAndView selectEntity(String id, String itemId){
        ModelAndView view = new ModelAndView("/cartUpdateOrSave");
        cart = cartService.selectByPrimaryKey(id);
        view.addObject("cart", cart);
        return view;
    }

    /**
     * 加入购物车
     */
    @RequestMapping(value = "/updateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject updateOrAddEntity(CartInfo cartInfo) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        // 判断购物车是否有商品
        Cart record = new Cart();
        record.setItemId(cartInfo.getItemId());
        int count = cartService.selectCount(record);
        // 购物车已存在该商品
        if (count >= 1) {
            returnInfo = new ReturnInfo(BaseConstant.FAIL, "购物车已存在该商品");
        } else {
            cart = new Cart();
            cart.setId(BaseUtil.uId());
            cart.setMemberId(cartInfo.getMemberId());
            cart.setItemId(cartInfo.getItemId());
            cart.setCreateTime(new Date());
            int id = cartService.insert(cart);
            if (id <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_INSERT);
            }
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    /**
     * 清空购物车
     */
    @RequestMapping(value = "/emptyCart",method = RequestMethod.POST)
    public @ResponseBody JSONObject emptyCart(String memberId, String cartJson) {
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(cartJson)) {
            returnInfo = new ReturnInfo(BaseConstant.FAIL, "请选择购物车中的商品！");
            jsonObject.put("returnInfo", returnInfo);
            return jsonObject;
        }
        returnInfo = cartService.emptyCart(memberId, cartJson);
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/deleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject deleteEntity(String id){
        ReturnInfo returnInfo = new ReturnInfo();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(id)) {
            returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            int ids = cartService.deleteByPrimaryKey(id);
            if (ids <= 0) {
                returnInfo = new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
            }
        }
        jsonObject.put("returnInfo", returnInfo);
        return jsonObject;
    }
}
